import {LoginOutput, PosAppProjectOutput} from 'api/pos'
import {WithShareState} from 'utils/shareState'
import {PosModule} from 'native-modules'
import {Toast} from 'components'
import {Alert} from 'react-native'
import {navigate} from './navigation'
interface Authorization extends LoginOutput {
  isLogin: boolean
  project: PosAppProjectOutput
  mac: string
  version: string
  lastOperateTime: Date
}
//@ts-ignore
const defaultLogin: Authorization = {isLogin: false, project: {}}
const WithAuthorization = WithShareState(defaultLogin)

export const getAuthorization = () => WithAuthorization.getShareState()
export const setLogin = async (data: LoginOutput) => {
  let project: PosAppProjectOutput = {}
  if (data.projectList && data.projectList.length > 0) {
    project = data.projectList[0]
  }
  let lastOperateTime = new Date()
  // setTimeout(() => { autoLoginOut(lastOperateTime) }, 10 * 60000)
  WithAuthorization.setShareState(() => ({...data, project, isLogin: true, lastOperateTime}))
}
export const setProject = async (project: PosAppProjectOutput) => {
  let data = WithAuthorization.getShareState()
  WithAuthorization.setShareState(() => ({...data, project}))
}
export const loginOut = () => {
  WithAuthorization.setShareState(defaultLogin)
}
export const setPosInfo = () => {
  PosModule.getPosInfo().then(res => {
    let data = WithAuthorization.getShareState()
    // Alert.alert(res.SN || '00-01-02-03-04-05')
    WithAuthorization.setShareState(() => ({...data, mac: res.SN || '00-01-02-03-04-05'}))
  })
}
export const setVersion = async (version: string) => {
  let data = WithAuthorization.getShareState()
  WithAuthorization.setShareState(() => ({...data, version}))
}
WithAuthorization.addListener(state => {
  console.log('state', JSON.stringify(state))
})

const autoLoginOut = (lastOperateTime: any) => {
  // let data = WithAuthorization.getShareState()
  // console.log('11', lastOperateTime)
  // console.log('11', data.lastOperateTime)
  // console.log('11', lastOperateTime === data.lastOperateTime)
  // if (data.isLogin && lastOperateTime === data.lastOperateTime) {
  // 	loginOut()
  // 	navigate('SignIn')
  // }
}

export const operate = async () => {
  return
  // let data = WithAuthorization.getShareState()
  // let lastOperateTime = new Date()
  // console.log('11', lastOperateTime)
  // setTimeout(() => { autoLoginOut(lastOperateTime) }, 10 * 60000)
  // WithAuthorization.setShareState(() => ({ ...data, lastOperateTime }))
}

export const useAuthorization = () => {
  const [state, setState] = WithAuthorization.useShareState()
  return {state, setLogin, loginOut}
}
